export default class ResizeModule {
    constructor(quill) {
        this.quill = quill;
        this.handle = null;
        this.selectedVideo = null;
        this.initHandlers();
    }

    initHandlers() {
        // 点击视频时显示调整手柄
        this.quill.root.addEventListener("click", (e) => {
            if (e.target.tagName === "VIDEO") {
                this.showResizeHandles(e.target);
            }
        });
    }

    showResizeHandles(video) {
        this.clearHandles();
        this.selectedVideo = video;

        // 创建调整手柄
        this.handle = document.createElement("div");
        this.handle.className = "ql-resize-handle";
        Object.assign(this.handle.style, {
            position: "absolute",
            width: "12px",
            height: "12px",
            background: "#369",
            cursor: "nwse-resize",
            border: "2px solid #fff",
        });

        // 定位手柄
        const rect = video.getBoundingClientRect();
        this.handle.style.left = `${rect.right - 15}px`;
        this.handle.style.top = `${rect.bottom - 15}px`;

        document.body.appendChild(this.handle);

        // 绑定拖拽事件
        this.handle.addEventListener("mousedown", this.startDrag.bind(this));
    }

    startDrag(e) {
        e.preventDefault();
        const startX = e.clientX;
        const startY = e.clientY;
        const startWidth = this.selectedVideo.offsetWidth;
        const startHeight = this.selectedVideo.offsetHeight;

        const doDrag = (e) => {
            const deltaX = e.clientX - startX;
            const deltaY = e.clientY - startY;
            this.selectedVideo.style.width = `${startWidth + deltaX}px`;
            this.selectedVideo.style.height = `${startHeight + deltaY}px`;
        };

        const stopDrag = () => {
            document.removeEventListener("mousemove", doDrag);
            document.removeEventListener("mouseup", stopDrag);
            this.saveSizeToContent();
        };

        document.addEventListener("mousemove", doDrag);
        document.addEventListener("mouseup", stopDrag);
    }

    saveSizeToContent() {
        const [blot] = Quill.find(this.selectedVideo);
        const value = {
            url: blot.value().url,
            width: this.selectedVideo.style.width,
            height: this.selectedVideo.style.height,
        };
        blot.replaceWith("customVideo", value);
    }

    clearHandles() {
        if (this.handle) {
            document.body.removeChild(this.handle);
            this.handle = null;
        }
    }
}
